<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class Warehouse_out extends AdminController
{
    public $_validation = null;

    function __construct()
    {
        parent::__construct();

        $this->load->model('MShop');
        $this->load->model('MShippingOut');
        $this->load->model('MAdmin');
        $allShops = $this->MShop->getAllShopsTrue();
        $allPurchaser = $this->MAdmin->getAllPurchaser();
        $this->_validation = Array(
            array('field' => 'shipping_person', 'label' => '发货人', 'rules' => 'required')
        , array('field' => 'in_ids', 'label' => '出库来源', 'rules' => 'required')
        , array('field' => 'shop_id', 'label' => '所属账户', 'rules' => 'integer|required')
        , array('field' => 'order_no', 'label' => '订单号', 'rules' => '')
        , array('field' => 'shipping_no', 'label' => '物流单号', 'rules' => 'required')
        , array('field' => 'shipping_no_trance', 'label' => '转运单号', 'rules' => '')
        , array('field' => 'city', 'label' => '发货城市', 'rules' => 'integer|required')
        , array('field' => 'shipping_type', 'label' => '物流方式', 'rules' => 'required')
        , array('field' => 'out_date', 'label' => '发货日期', 'rules' => 'required')
        , array('field' => 'out_type', 'label' => '出库类型', 'rules' => 'required')
        , array('field' => 'quantity', 'label' => '数量', 'rules' => 'integer')
        , array('field' => 'cost', 'label' => '成本', 'rules' => 'required')
        , array('field' => 'boxes', 'label' => '打包箱数', 'rules' => 'integer|required')
        , array('field' => 'freight', 'label' => '运费', 'rules' => '')
        , array('field' => 'remark', 'label' => '备注', 'rules' => '')
        , array('field' => 'status', 'label' => '状态', 'rules' => 'required')
        , array('field' => 'update_time', 'label' => '更新时间', 'rules' => '')
        );
        $this->assign('allShops', $allShops);
        $this->assign('allPurchaser', $allPurchaser);
    }

    public function index()
    {
        $this->load->library('FormFilter');
        $this->load->helper('formfilter');
        $this->formfilter->addFilter('order_no', 'like');
        $this->formfilter->addFilter('shipping_no', 'like');
        $this->formfilter->addFilter('shipping_person', 'like');
        $this->formfilter->addFilter('shop_id', 'where');
        $this->formfilter->addFilter('out_type', 'where');
        $this->formfilter->addFilter('city', 'where');
        $this->formfilter->addFilter('status', 'where');

        if ($begintime = filterValue('out_create_time_begin')) {
            $this->formfilter->addFilter('out_create_time_begin', 'where', array('out_date >= ', strtotime($begintime . ' 00:00:00')));
        }
        if ($endtime = filterValue('out_create_time_end')) {
            $this->formfilter->addFilter('out_create_time_end', 'where', array('out_date <= ', strtotime($endtime . ' 23:59:59')));
        }

        $number_perpage = filterValue('out_number_perpage');
        $order_type = filterValue('out_order_type');

        $total_number = $this->MShippingOut->getCount();
        $limit = $this->pagination($total_number, '', $number_perpage);
        $list = $this->MShippingOut->getList($limit, $order_type);
        $this->assign('list', $list);
        $this->layout();
    }

    public function add()
    {
        $data = $this->input->post();
        $in_ids = $data['in_ids'];

        $obj = $this->MShippingOut->createVo();
        $obj->operator_id = $this->_user->id;
        $obj->in_ids = implode($in_ids, ',');
        $this->load->model('MShippingIn');
        $in_list = $this->MShippingIn->getInList($obj->in_ids);

        $this->assign('obj', $obj);
        $this->assign('list', $in_list);
        $this->layout();
    }

    public function add_post()
    {
        $this->db->trans_start();
        $quantities = $this->input->post('quantities');
        $shop = $this->MShop->getOne(['id' => $this->input->post('shop_id')]);
        $obj = $this->MShippingOut->createVo();
        $this->load->library('form_validation');
        $this->form_validation->set_rules($this->_validation);
        if ($this->form_validation->run() == TRUE) {
            $this->load->helper('populate');
            $newObj = populate((Object)((Array)$obj), $this->form_validation->post());
            $newObj->out_date = strtotime($this->input->post('out_date'));
            $newObj->operator_id = $this->_user->id;
            $newObj->group_id = $shop->group_id;
            $newObj->in_ids = implode(',',$newObj->in_ids);
            $result = $this->MShippingOut->add($newObj);
            if (!$result) {
                $this->db->_trans_status = false;
            } else {
                //写入操作记录
                $content = ' 新增出库记录: ';
                foreach ($newObj as $key => $value) {
                    if ($key == 'cost' || $key == 'freight') {
                        $newObj->$key = (float)$newObj->$key;
                    }

                    //给数字赋值
                    if ($key == 'shop_id') {
                        $allShops = $this->MShop->getAllShopsTrue();
                        $newObj->shop_id = $allShops[$newObj->shop_id];
                    }
                    if ($key == 'city') {
                        $newObj->city = IOSS_StaticConfig::getShippingWarehouse($newObj->city);
                    }
                    if ($key == 'out_type') {
                        $newObj->out_type = IOSS_StaticConfig::getShippingOutType($newObj->out_type);
                    }
                    if ($key == 'out_date') {
                        $newObj->out_date = date('Y-m-d', $newObj->out_date);
                    }
                    if ($key !== 'update_time' && $key !== 'create_time') {
                        $content .= $key . ' 为 ' . $newObj->$key . ';';
                    }
                }

                if ($this->input->post('status') == 1) {
                    foreach ($quantities as $k => $v) {
                        $this->load->model('MShippingIn');
                        $detail = $this->MShippingIn->getOne(['id' => $k]);
                        $detail->left_quantity -= $v;
                        if (!$this->MShippingIn->update($detail)){
                            $this->db->_trans_status = false;
                        }
                        $content .= ' ID为'.$k.'入库记录，出库数量为：'.$v.'; ';
                    }
                }

                if ($content) {
                    $this->shippingLog($this->_user->id, $result, $this->_thisModule . $this->_thisController . '/' . $this->_thisMethod, $content,0);
                }
            }

            $this->db->trans_complete();
            if ($this->db->trans_status() !== FALSE) {
                successAndRedirect('添加记录成功');
            } else {
                errorAndRedirect('添加失败');
            }

        } else {
            $data = $this->input->post();

            $in_ids = implode($data['in_ids'],',');
            $this->load->model('MShippingIn');
            $in_list = $this->MShippingIn->getInList($in_ids);
            $this->assign('list', $in_list);
        }
        $this->assign('obj', $obj);
        $this->layout('form.tpl');
    }

    function edit($id)
    {
        if (!is_numeric($id)) {
            show_error(l('id_not_null'));
        }
        $obj = $this->MShippingOut->getOne(Array('id' => $id));
        if (!$obj) {
            errorAndRedirect('未找到定义！');
        }

        //获取对应的入库记录
        $in_ids = $obj->in_ids;
        $this->load->model('MShippingIn');
        $in_list = $this->MShippingIn->getInList($in_ids);
        $shop = $this->MShop->getOne(['id' => $this->input->post('shop_id')]);
        $this->editObj = $obj;
        $obj->out_date = date('Y-m-d', $obj->out_date);
        $this->load->library('form_validation');
        $this->form_validation->set_rules($this->_validation);

        if ($this->form_validation->run() == TRUE) {
            $this->load->helper('populate');
            $newObj = populate((Object)((Array)$obj), $this->form_validation->post());
            $newObj->out_date = strtotime($this->input->post('out_date'));
            $newObj->group_id = $shop->group_id;
            if ($this->MShippingOut->update($newObj)) {
                //写入操作记录
                $content = ' 更新出库记录: ';
                foreach ($newObj as $key => $value) {
                    if ($key == 'cost' || $key == 'freight') {
                        $newObj->$key = (float)$newObj->$key;
                        $obj->$key = (float)$obj->$key;
                    }

                    //给数字赋值
                    if ($key == 'shop_id') {
                        $allShops = $this->MShop->getAllShopsTrue();
                        $newObj->shop_id = $allShops[$newObj->shop_id];
                        $obj->shop_id = $allShops[$obj->shop_id];
                    }

                    if ($key == 'status') {
                        $newObj->status = MShippingOut::getState($newObj->status);
                        $obj->status = MShippingOut::getState($obj->status);
                    }

                    if ($key == 'city') {
                        $newObj->city = IOSS_StaticConfig::getShippingWarehouse($newObj->city);
                        $obj->city = IOSS_StaticConfig::getShippingWarehouse($obj->city);
                    }

                    if ($key == 'out_type') {
                        $newObj->out_type = IOSS_StaticConfig::getShippingOutType($newObj->out_type);
                        $obj->out_type = IOSS_StaticConfig::getShippingOutType($obj->out_type);
                    }

                    if ($key == 'out_date') {
                        $newObj->out_date = date('Y-m-d', $newObj->out_date);
                    }

                    if ($newObj->$key !== $obj->$key && $key !== 'update_time' && $key !== 'create_time') {

//                        $content .= ' '.IOSS_StaticConfig::translateLogField($key).' 由 '.$obj->$key.' 改为 '.$newObj->$key.';';
                        $content .= $key . ' 由 ' . $obj->$key . ' 改为 ' . $newObj->$key . ';';
                    }
                }
                if ($content) {
                    $this->shippingLog($this->_user->id, $id, $this->_thisModule . $this->_thisController . '/' . $this->_thisMethod, $content,0);
                }
                successAndRedirect(l('edit_success'));
            } else {
                $this->db->trans_complete();
                errorAndRedirect(l('data_fail'));
            }
        }
        $this->assign('list', $in_list);
        $this->assign('obj', $obj);
        $this->layout();
    }

    function view($id)
    {
        if (!is_numeric($id)) {
            show_error(l('id_not_null'));
        }
        $this->load->library('FormFilter');
        $this->load->helper('formfilter');
        $obj = $this->MShippingOut->getOne(Array('id' => $id));
        if (!$obj) {
            errorAndRedirect('未找到定义！');
        }
        $in_ids = $obj->in_ids;
        $this->load->model('MShippingIn');
        $in_list = $this->MShippingIn->getInList($in_ids);

        $this->load->model('MShippingLog');
        $logs = $this->MShippingLog->getAllOutLog($id);

        $this->assign('obj', $obj);
        $this->assign('logs', $logs);
        $this->assign('list', $in_list);
        $this->layout('view.tpl');
    }

    function delete($id, $update_time)
    {
        if (!is_numeric($id) || !is_numeric($update_time)) {
            show_error(l('id_not_null'));
        }

        $newObj = $this->MShippingOut->getById($id);

        //写入操作记录
        $content = ' 删除出库记录: ';
        foreach ($newObj as $key => $value) {
            if ($key == 'cost' || $key == 'freight') {
                $newObj->$key = (float)$newObj->$key;
            }

            //给数字赋值
            if ($key == 'shop_id') {
                $allShops = $this->MShop->getAllShopsTrue();
                $newObj->shop_id = $allShops[$newObj->shop_id];
            }

            if ($key == 'status') {
                $newObj->status = MShippingOut::getState($newObj->status);
            }

            if ($key == 'out_date') {
                $newObj->out_date = date('Y-m-d', $newObj->out_date);
            }

            if ($key == 'city') {
                $newObj->city = IOSS_StaticConfig::getShippingWarehouse($newObj->city);
            }

            if ($key == 'out_type') {
                $newObj->out_type = IOSS_StaticConfig::getShippingOutType($newObj->out_type);
            }

            if ($key == 'operator_id') {
                $allPurchaser = $this->MAdmin->getAllPurchaser();
                $newObj->operator_id = $allPurchaser[$newObj->operator_id];
            }

            if ($key !== 'update_time' && $key !== 'create_time') {
//                        $content .= ' 新增入库记录：' . IOSS_StaticConfig::translateLogField($key) . ' 为 ' . $obj->$key . $newObj->$key . ';';
                $content .= $key . ' 为 ' . $newObj->$key . ';';
            }
        }

        if (!$this->MShippingOut->delete($id, $update_time)) {
            errorAndRedirect(l('data_fail'));
        } else {
            if ($content) {
                $this->shippingLog($this->_user->id, $id, $this->_thisModule . $this->_thisController . '/' . $this->_thisMethod, $content,0);
            }
            successAndRedirect(l('delete_success'));
        }
    }
}
